#coding=utf-8
import pandas as pd
import os
import re
import logging
from timeout_func import *

class_csvs = {
           # "201":"201.csv",
              "202":"202.csv",
              "203":"203.csv"}
NAME_FIELD = '姓名'
GIT_ADDRESS_FIELD= 'gitee路径'

work_dir = r'D:\sfxy20-21-1\gits'

path = os.path.abspath(os.curdir)
logging.basicConfig(filename="{}/log.log".format(work_dir),level = logging.INFO
                    ,filemode='a')

def process_row(row):
    url = row[GIT_ADDRESS_FIELD]
    repo_name_ok = 1 if not pd.isna(url) and 'bigdata' in url else 0
    if not pd.isna(url):
        repo_names = re.split(r'(?<!/)/(?!/)', url)
        try:
            user_name = repo_names[1]
            repo_name = 'bigdata' if len(repo_names)<3 else repo_names[2]
        except:
            print(url, repo_names)
        row['user'] = user_name
        row['repo_name'] = repo_name
    else:
        repo_name_ok = -1
    row['repo_ok'] = repo_name_ok
    return row


for d, csv in class_csvs.items():
    logging.info("=={}========================".format(d))
    curt_class_path = work_dir + "/" + d
    os.mkdir(curt_class_path) if not os.path.exists(curt_class_path) else None

    df = pd.read_csv(work_dir + "/" + csv, sep='\t')
    students = df.apply(process_row, axis=1)

    os.chdir(curt_class_path)

    for index, row in students.iterrows():
        if row['repo_ok'] >= 0:
            gitee_url = "https://gitee.com/{}/{}".format(row['user'], row['repo_name'])
            repo_path = curt_class_path + "/{}{}".format(row['学号'], row['姓名'])

            work_path, cmd = (repo_path,       "git pull ") if os.path.exists(repo_path) else\
                             (curt_class_path, "git clone {} {}{}".format(gitee_url, row['学号'], row['姓名']))

            os.chdir(work_path)
            print(row['姓名'], gitee_url, end=' ')
            try:
                stdout = command(cmd, 60)
                print(stdout.decode("utf-8"))
                logging.info(cmd)
                logging.info( "{} {} {}".format(row['学号'], row['姓名'], stdout.decode("utf-8")))
            except TimeoutError as e:
                logging.error( "TIMEOUT {} {}".format(row['学号'], row['姓名']))
        else:
            print(row)
            logging.error("{} {}".format(row['学号'], row['姓名']))
